package com.acme.bankapp.service.bank;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.exceptions.BankException;
import com.acme.bankapp.exceptions.ClientExistsException;

public class BankService {

	public static boolean addClient(Bank bank, Client client)
			throws IOException {

		try {
			bank.addClient(client);
			return true;
		} catch (ClientExistsException e) {
			System.out.println("Client already exist");
		}
		return false;
	}

	public static void modifyBank(Bank bank, Client client, int amount)
			throws BankException {
		client.getAccount().withdraw(amount);
	}

	public static void printBalance(Bank bank) {
		for (Client client : bank.getClients()) {
			System.out.println(client.getAccount().getBalance());
		}
	}

	public static void printMaximumAmountToWithdraw(Bank bank) {
		for (Client client : bank.getClients()) {
			System.out.println(client.getAccount().maximumAmountToWithdraw());
		}
	}

	public static void showBank(Bank bank) {

		System.out.println("Clients of " + bank.getName() + " :");
		System.out.println("-------------------");
		for (Client client : bank.getClients()) {
			System.out.println(client.getClientSalutation());
		}
		System.out.println("-------------------");

	}

	public static void saveBank(Bank bank, File f) throws IOException{
		if (!f.exists()){
			f.createNewFile();
		}
		FileOutputStream fileStream = null;
		ObjectOutputStream objectStream = null;
		try{
			fileStream = new FileOutputStream(f);
			objectStream = new ObjectOutputStream(fileStream);
			
			objectStream.writeObject(bank);
		}catch (IOException e){
			System.out.println(e.getMessage() );
		}finally {
			try{
				objectStream.close();
				fileStream.close();
			}catch (IOException e) {
				System.out.println(e.getMessage() );
			}
		}
	}

	public static Bank readBank(File f) throws IOException,
			ClassNotFoundException {

		if (!f.exists()) {
			throw new IOException("DataBase is missing");
		}
		
		FileInputStream fileStream = null;
		ObjectInputStream objectStream = null;
		Bank bank = null;
		
		try{
			fileStream = new FileInputStream(f);
			objectStream = new ObjectInputStream(fileStream);
	
			Object restored = objectStream.readObject();
			if (restored instanceof Bank) {
				bank = (Bank) restored;
			}
		}catch (IOException e){
			System.out.println(e.getMessage() );
		}finally {
			try{
				objectStream.close();
				fileStream.close();
			}catch (IOException e) {
				System.out.println(e.getMessage() );
			}
		}
		return bank;
	}
}
